// 药品配送地址
import React from 'react';
import {Modal, Input, Select, DatePicker, Form, message} from 'antd';
import { $http } from 'containers/config/https';
import Moment from 'moment';

const {Option} = Select;
const { TextArea } = Input;
const FormItem = Form.Item;

class DrugDeliveryAddress extends React.Component {
  constructor() {
    super();
    var userData = JSON.parse(sessionStorage.getItem('userData'));
    this.state = {
      userData,
      visible: false,
      methods: 0,
      rowData: {},
      provinceSelectData: [], // 省下拉数据
      cityIdSelectData: [], // 市下拉数据
      areaSelectData: [], // 区下拉数据
      villageSelectData: [], // 街道下拉框数据
      userInfo: {}, // 选中行form数据
    }
  }

  componentDidMount() {
    this.props.onRef(this);
  }

  // 获取主列表columns
  getTableColumns = () => {
    let {userData} = this.state;
    let data = {
      params: [{
        compontName: "DrugDeliveryAddress",
        reactCode: ['DrugDeliveryAddress']
      }]
    }
    $http.post('urlS', this, {
      code: '01040073',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({
            localeProvider: userData.language == 'EN' ? res.result.language.EN : res.result.language.CN
          })
        }
      }
    })
  }

	//国际化
	setMessage = (name, message, defaultTitle) => {
		return this.state.localeProvider&&this.state.localeProvider[name] ? this.state.localeProvider[name][message] : defaultTitle
  }

  // 获取市下拉数据
  getCityIdSelectData = (provinceId) => {
    let data = {
      params: [{
        provinceId, // 市ID
      }]
    }
    $http.post('urlS', this, {
      code: '02070004',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({cityIdSelectData: res.result})
        }
      }
    })
  }

  // 获取区下拉数据
  getAreaSelectData = (cityId) => {
    let data = {
      params: [{
        cityId, // 市ID
      }]
    }
    $http.post('urlS', this, {
      code: '02070005',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({areaSelectData: res.result})
        }
      }
    })
  }

  // 获取街道下拉数据
  getVillageSelectData = (areaId) => {
    let data = {
      params: [{
        areaId, // 区ID
      }]
    }
    $http.post('urlS', this, {
      code: '02070006',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({villageSelectData: res.result})
        }
      }
    })
  }

  // 获取默认地址
  getDefaultAddress = () => {
    let {rowData, methods} = this.state;
    let data = {
      params: [{
        KMID: rowData&&rowData.KMID, // 康美处方ID
        methods, // 配送方式
        patID: rowData&&rowData.patID, // 病人ID
      }]
    }
    $http.post('urlS', this, {
      code: '02070008',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({userInfo: res.result}, () => {
            // 获取区以及街道地址
            this.getAreaSelectData(this.state.userInfo.cityID);
            this.getVillageSelectData(this.state.userInfo.areaID);
          })
        }
      }
    })
  }

  // 打开弹窗
  handleShowModal = (rowData, selectData, methods) => {
    console.log('弹窗数据', rowData)
    let {userData} = this.state;
    let provinceSelectData = selectData && selectData.province ? selectData.province : [];
    let cityIdSelectData = selectData && selectData.city ? selectData.city : [];
    this.setState({visible: true, rowData, cityIdSelectData, provinceSelectData, methods}, () => {
      // this.getDefaultAddress();
      this.getAreaSelectData(this.state.rowData.cityID);
      this.getVillageSelectData(this.state.rowData.areaID);
      !this.state.localeProvider && userData.language == 'EN' ? this.getTableColumns() : "";
    });
    // let that = this;
    // setTimeout(() => {
    //   that.setState({rowData})
    // }, 1000)
  }

  // 关闭弹窗
  handleCancel = () => {
    this.setState({visible: false});
    this.props.form.resetFields(); //清空所有
  }

  // 输入下拉框option
  exportSelectOption = (data) => {
		let selectOption = data && data.map((item, index) => {
			return (<Option key={index} value={item.descripts} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
    })
    return selectOption;
  }

  // 选择省查询市数据
  handleProvinceSelect = e => {
    let a =  this.state.provinceSelectData.length>0&&this.state.provinceSelectData.filter((item)=> item.descripts == e).length>0?this.state.provinceSelectData.filter((item)=> item.descripts == e)[0]:[];
    this.getCityIdSelectData(a.id);
    this.props.form.setFieldsValue({
      cityID: undefined, // 市
      areaID: undefined, // 区
      villageID: undefined, // 街道
    })
  }

  // 选择市查询区数据
  handleCitySelect = e => {
    let a =  this.state.cityIdSelectData.length>0&&this.state.cityIdSelectData.filter((item)=> item.descripts == e).length>0?this.state.cityIdSelectData.filter((item)=> item.descripts == e)[0]:[];
    this.getAreaSelectData(a.id);
    for(var i = 0; i < this.state.cityIdSelectData.length; i++) {
      if (this.state.cityIdSelectData[i].id === e) {
        // 默认选上该市属于的省
        this.props.form.setFieldsValue({
          provinceID: this.state.cityIdSelectData[i].province, // 省
          areaID: undefined, // 区
          villageID: undefined, // 街道
        })
        return;
      }
    }
  }

  // 选择区查询街道数据
  handleAreaSelect = e => {
    let a =  this.state.areaSelectData.length>0&&this.state.areaSelectData.filter((item)=> item.descripts == e).length>0?this.state.areaSelectData.filter((item)=> item.descripts == e)[0]:[];
    this.getVillageSelectData(a.id);
    this.props.form.setFieldsValue({
      villageID: undefined, // 街道
    })
  }

  // 确认
  handleOk = () => {
    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      // 验证成功
      if (errors === null) {
        let data = {
          params: []
        }

        let obj = JSON.parse(JSON.stringify(values));
        obj.orderID = this.state.rowData.expID ? this.state.rowData.expID : '';
        obj.patientID = this.state.rowData&&this.state.rowData.patID ? this.state.rowData.patID : "";
        obj.admID = this.state.rowData&&this.state.rowData.admID ? this.state.rowData.admID : "";
        obj.userID  = this.state.userData.userID?this.state.userData.userID:'';
        obj.sendStartDate = obj.sendDate ? Moment(obj.sendDate).format('YYYY-MM-DD') : "";
        obj.cmpresc = [this.state.rowData.ordPrescNo];
        obj.hospCode = this.state.userData.hospCode?this.state.userData.hospCode:'';
        obj.selfPickFlag = 'N';

        // 处理需要传递的obj
        data.params.push(obj);

        if( this.state.rowData.expID){
          $http.post('urlADS', this, {
            code: "03030062",
            data: data,
            success: function (res) {
              if (+res.errorCode === 0) {
                message.success(res.errorMessage);
                this.handleCancel();
                this.props.handleQuery();
              }
            }
          })
        }else {
          $http.post('urlADS', this, {
            code: "03030060",
            data: data,
            success: function (res) {
              if (+res.errorCode === 0) {
                message.success(res.errorMessage);
                this.handleCancel();
                this.props.handleQuery();
              }
            }
          })
        }

      }
    });
  }

  render() {
    let {visible, provinceSelectData, cityIdSelectData, areaSelectData, villageSelectData, userInfo, methods, userData,rowData} = this.state;
    const { getFieldDecorator } = this.props.form;

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: userData&&userData.language == 'EN' ? 10 : 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: userData&&userData.language == 'EN' ? 14 : 18 },
      },
      labelAlign: "right"
    };
    return (
      <Modal
        title={<div>{this.setMessage("DrugDeliveryAddressDelivery_address", "descripts", "配送地址")}({methods === 1 ? this.setMessage("DrugDeliveryAddressHospital", "descripts", "医院") : this.setMessage("DrugDeliveryAddressHome", "descripts", "家里")})</div>}
        visible={visible}
        onOk={this.handleOk}
        onCancel={this.handleCancel}
      >
        <Form {...formItemLayout}>
          <FormItem label={this.setMessage("DrugDeliveryAddressConsignee", "descripts", "收货人：")}>
            {getFieldDecorator('receiveName', {
              initialValue: rowData.consignee ? rowData.consignee: undefined,
              rules: [{ required: true, message: this.setMessage("DrugDeliveryAddressConsignee", "message", "收货人不能为空") }]
            })(
              <Input placeholder={this.setMessage("DrugDeliveryAddressPlease_input", "descripts", "请输入")} className='input' />
            )}
          </FormItem>
          <FormItem label={this.setMessage("DrugDeliveryAddressContactNumber", "descripts", "联系电话：")}>
            {getFieldDecorator('receiveMobile', {
              initialValue:rowData.telephone ? rowData.telephone: undefined,
              rules: [{ required: true, message: this.setMessage("DrugDeliveryAddressContactNumber", "message", "联系电话不能为空") }]
            })(
              <Input placeholder={this.setMessage("DrugDeliveryAddressPlease_input", "descripts", "请输入")} className='input' />
            )}
          </FormItem>
          <FormItem label={this.setMessage("DrugDeliveryAddressDelivery_date", "descripts", "配送日期：")}>
            {getFieldDecorator('sendDate', {
              initialValue:rowData.deliveryDate ? Moment(rowData.deliveryDate): undefined,
            })(
              <DatePicker placeholder={this.setMessage("DrugDeliveryAddressPlease_choose", "descripts", "请选择")} allowClear={false} style={{width: "100%"}} />
            )}
          </FormItem>
          <FormItem label={this.setMessage("DrugDeliveryAddressProvince", "descripts", "省：")}>
            {getFieldDecorator('receiveProvinceDesc', {
              initialValue:rowData.provDesc ? rowData.provDesc: undefined,
              rules: [{ required: true, message: this.setMessage("DrugDeliveryAddressProvince", "message", "省不能为空") }]
            })(
              <Select showSearch optionFilterProp="seatchprop" allowClear placeholder={this.setMessage("DrugDeliveryAddressPlease_choose", "descripts", "请选择")} onSelect={this.handleProvinceSelect}>
                {this.exportSelectOption(provinceSelectData)}
              </Select>
            )}
          </FormItem>
          <FormItem label={this.setMessage("DrugDeliveryAddressCity", "descripts", "市：")}>
            {getFieldDecorator('receiveCityDesc', {
              initialValue:rowData.cityDesc ? rowData.cityDesc: undefined,
              rules: [{ required: true, message: this.setMessage("DrugDeliveryAddressCity", "message", "市不能为空") }]
            })(
              <Select showSearch optionFilterProp="seatchprop" allowClear placeholder={this.setMessage("DrugDeliveryAddressPlease_choose", "message", "请选择")} onSelect={this.handleCitySelect}>
                {this.exportSelectOption(cityIdSelectData)}
              </Select>
            )}
          </FormItem>
          <FormItem label={this.setMessage("DrugDeliveryAddressDistrict", "descripts", "区：")}>
            {getFieldDecorator('receiveAreaDesc', {
              initialValue:rowData.areaDesc ? rowData.areaDesc: undefined,
              rules: [{ required: true, message: this.setMessage("DrugDeliveryAddressDistrict", "message", "区不能为空") }]
            })(
              <Select showSearch optionFilterProp="seatchprop" allowClear placeholder={this.setMessage("DrugDeliveryAddressPlease_choose", "message", "请选择")} onSelect={this.handleAreaSelect}>
                {this.exportSelectOption(areaSelectData)}
              </Select>
            )}
          </FormItem>
          <FormItem label={this.setMessage("DrugDeliveryAddressStreet", "descripts", "街道：")}>
            {getFieldDecorator('receiveVillageDesc', {
              initialValue:rowData.villageDesc ? rowData.villageDesc: undefined,
              rules: [{ required: true, message: this.setMessage("DrugDeliveryAddressStreet", "message", "街道不能为空") }]
            })(
              <Select showSearch optionFilterProp="seatchprop" allowClear placeholder={this.setMessage("DrugDeliveryAddressPlease_choose", "message", "请选择")} >
                {this.exportSelectOption(villageSelectData)}
              </Select>
            )}
          </FormItem>
          <FormItem label={this.setMessage("DrugDeliveryAddressDetailed_address", "descripts", "详细地址：")}>
            {getFieldDecorator('receiveAdress', {
              initialValue:rowData.address ? rowData.address: undefined,
              rules: [{ required: true, message: this.setMessage("DrugDeliveryAddressDetailed_address", "message", "详细地址不能为空") }]
            })(
              <TextArea rows={2} />
            )}
          </FormItem>
        </Form>
      </Modal>
    )
  }
};
const DrugDeliveryAddressForm = Form.create()(DrugDeliveryAddress);
export default DrugDeliveryAddressForm;
